<?php

require_once(dirname(dirname(__FILE__)) . '/include/core.php');

#能走到这里就说明校验已经通过了
// extract($_POST);

// $data = json_decode(base64_decode($data),true);

/*
 * 将php格式整理成Json
 *
	$_fields = include(dirname(__FILE__) . '/fields.php');
	$fields = array();
	foreach($_fields as $f){
		$fields[$f[0]] = array(
			'type' => $f[2],
			'info' => $f[1],
			'empty' => $f[3]
		);
	}
*/

$fields = json_decode(file_get_contents('fields.json'),true);

#如果有多余的字段，直接报错
$errors = array();

if(!isset($data['goods'])){
	send(DATA_ERROR);
}

if(count($data['goods']) > 500){
	send(NUMBER_ERROR);
}

$data = $data['goods'];

if(!count($data)){
	send(NUMBER_ERROR);
}

if(is_assoc($data)){
	send(DATA_ERROR);
}

#只检查前500单
for($i = 0; $i < count($data); $i++){
	#如果不存在goods_id，直接报错
	if(!isset($data[$i]['goods_id'])){
		unset($data[$i]);
		continue;
	}

	#没有错误的情况修正数据
	$data[$i]['store_id'] = $has_store['store_id'];
	$data[$i]['store_id_first'] = $has_store['store_id_first'];
	$data[$i]['store_id_second'] = $has_store['store_id_second'];
	$data[$i]['datetime_input'] = date('Y-m-d H:i:s');

	$error = check_single_item($data[$i],$fields);

	#如果有错误
	if($error){
		$errors[] = $data[$i]['goods_id'];
		unset($data[$i]);
		continue;
	}

	#继续修正部分数据
	if(empty($data[$i]['goods_promotion_price'])){
		$data[$i]['goods_promotion_price'] = $data[$i]['goods_price'];
	}


	#查找该商品是否存在
	$has_this_goods = Model()->table('goods_stock')->where(array('goods_id' => $data[$i]['goods_id'],'store_id'=> $store_id))->find();
	if($has_this_goods){
		$data[$i]['id'] = $has_this_goods['id'];
	}

	// $data[$i]['status_shangjian'] = 0;
	// $data[$i]['status_haiguan'] = 0;

	
}

if(!count($data)){
	send(ALL_ERROR);
}

#全部通过，插入数据库
$model = Model('goods_stock');
foreach($data as $key => $val){
	if(empty($val)){
		continue;
	}
	
	$id = $model->insert($val,true);

	if(!$id){
		$errors[] = $data[$i]['goods_id'];
	}
}

if(count($errors)){
	send(SOME_SUCCESS,$errors);
}
else{
	send(RESPONSE_SUCCESS);
}




